<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      </BasicForm>

      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="openCreateDrawer(true)">
            <template #icon>
              <n-icon>
                <PlusOutlined/>
              </n-icon>
            </template>
            添加角色
          </n-button>
        </template>

        <template #action>
          <TableAction/>
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editRoleTitle">
      <div class="py-3 menu-list">
        <n-tree
          block-line
          checkable
          :virtual-scroll="true"
          :data="treeData"
          :expandedKeys="expandedKeys"
          :checked-keys="checkedKeys"
          style="max-height: 950px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="onExpandedKeys"
        />
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="packHandle">
            全部{{ expandedKeys.length ? '收起' : '展开' }}
          </n-button>

          <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>
    <CreateDrawer ref="createDrawerRef"/>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref, unref, h, onMounted, inject} from 'vue';
import {useDialog, useMessage} from 'naive-ui';
import {BasicTable, TableAction} from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import {delRole, editRole, editRoleMenu, getRoleList} from '@/api/system/role';
import {getMenuList} from '@/api/system/menu';
import {columns} from './columns';
import {PlusOutlined} from '@vicons/antd';
import {getTreeAll} from '@/utils';
import {useRouter} from 'vue-router';
import CreateDrawer from './CreateDrawer.vue';

const reloadPage = inject('reloadPage') as Function;

const schemas: FormSchema[] = [
  {
    field: 'name',
    component: 'NInput',
    label: '角色名',
    componentProps: {
      placeholder: '请输入角色名',
      onInput: (e: any) => {
        searchForm.value.name = e;
      },
    },
  },
  {
    field: 'isDefault',
    component: 'NSelect',
    label: '默认角色',
    componentProps: {
      placeholder: '请选择是否默认角色',
      options: [
        {
          label: '是',
          value: '1',
        },
        {
          label: '否',
          value: '0',
        },
      ],
      onUpdateValue: (e: any) => {
        searchForm.value.isDefault = e;
      },
    },
  },
  {
    field: 'status',
    component: 'NSelect',
    label: '是否启用',
    componentProps: {
      placeholder: '请选择是否启用',
      options: [
        {
          label: '是',
          value: 'enable',
        },
        {
          label: '否',
          value: 'disable',
        },
      ],
      onUpdateValue: (e: any) => {
        searchForm.value.status = e;
      },
    },
  },
];

const router = useRouter();
const message = useMessage();
const actionRef = ref();
const createDrawerRef = ref();

const dialog = useDialog();
const showModal = ref(false);
const formBtnLoading = ref(false);
const checkedAll = ref(false);
const editRoleTitle = ref('');
const treeData = ref([]);
const expandedKeys = ref([]);
const checkedRecordId = ref('');
const checkedKeys = ref([]);

const defaultValueRef = () => ({
  name: undefined,
  isDefault: null,
  status: undefined,
});

const searchForm = ref(defaultValueRef())

const params = reactive({
  pageSize: 10,
});

const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: [
        {
          label: '菜单权限',
          onClick: handleMenuAuth.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          auth: ['role_menu_list'],
        },
        {
          label: '编辑',
          onClick: handleEdit.bind(null, record),
          ifShow: () => {
            return true;
          },
          auth: ['role_edit'],
        },
        {
          label: '删除',
          onClick: handleDelete.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          auth: ['role_del'],
        },
      ],
    });
  },
});

const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 s:2 s:3 s:4 s:5' },
  labelWidth: 80,
  showAdvancedButton: false,
  schemas,
});

const loadDataTable = async (params: any) => {
  params = {
    ...params,
    ...searchForm.value,
  }
  const response = await getRoleList(params)
  return response.data;
};

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function openCreateDrawer(isInit: boolean = false) {
  createDrawerRef.value.openDrawer(isInit);
}

function reloadTable() {
  actionRef.value.reload();
}

function confirmForm(e: any) {
  e.preventDefault();
  formBtnLoading.value = true;
  setTimeout(() => {
    editRoleMenu({
      id: checkedRecordId.value,
      menu_keys: checkedKeys.value,
    }).then(res => {
      if (res.code === 200) {
        message.success(res.message);
      } else {
        message.error(res.message);
      }
      showModal.value = false;
      reloadTable();
      formBtnLoading.value = false;
    })

  }, 200);
}

function handleEdit(record: Recordable) {
  Object.assign(createDrawerRef.value.formParams, record);
  openCreateDrawer(false);
}

function handleDelete(record: Recordable) {
  dialog.info({
    title: '提示',
    content: `您确定想删除此角色吗?`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      delRole(record.id).then(res => {
        if (res.code === 200) {
          message.success('删除成功', {
            duration: 1000,
            closable: true,
          });
          reloadPage();
        } else {
          message.error(res.message, {
            duration: 1000,
            closable: true,
          });
        }
      })
    },
    onNegativeClick: () => {
      message.error('已取消');
    },
  });
}


function handleSubmit(values: Recordable) {
  actionRef.value.updatePage(1);
}

function handleReset(values: Recordable) {
  Object.assign(searchForm.value, defaultValueRef())
}

function handleMenuAuth(record: Recordable) {
  editRoleTitle.value = `分配 ${record.name} 的菜单权限`;
  checkedRecordId.value = record.id;
  checkedKeys.value = record.menu_keys;
  showModal.value = true;
}

function checkedTree(keys) {
  checkedKeys.value = keys;
}

function onExpandedKeys(keys) {
  expandedKeys.value = keys;
}

function packHandle() {
  let keys = []
  if (!expandedKeys.value.length) {
    keys = packAllKey(unref(treeData))
  }
  expandedKeys.value = keys
}

function packAllKey(listData: any[]) {
  let arr = listData.map((item: any) => item.key as string) as []
  listData.forEach((data: { children: [] }) => {
    if (data.children && data.children.length > 0) {
      arr = [...arr, ...packAllKey(data.children)]
    }
  })
  return arr
}

function checkedAllHandle() {
  if (!checkedAll.value) {
    checkedKeys.value = [ ...getTreeAll(treeData.value) ] as [];
    checkedAll.value = true;
  } else {
    checkedKeys.value = [];
    checkedAll.value = false;
  }
}

onMounted(async () => {
  const treeMenuList = await getMenuList({ _all: 1});
  treeData.value = treeMenuList.data;
  expandedKeys.value = packAllKey(unref(treeData))
});
</script>

<style lang="less" scoped></style>
